package com.study.webapp.jdk8;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

/**
 * @program: study
 *
 * @description:
 *
 * @author: heqiang
 *
 * @create: 2020-05-06 15:45
 **/
public class ConditionTest {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Producer producer = new Producer("生产者",lock,condition);
        Consumer consumer = new Consumer("消费者",lock,condition);
        Thread t1 = new Thread(producer);
        Thread t2 = new Thread(consumer);
        t2.start();
        t1.start();
    }



    static class Consumer implements Runnable {
        private String name;
        private Lock lock;
        private Condition condition;

        public Consumer(String name,Lock lock,Condition condition) {
            this.name = name;
            this.lock = lock;
            this.condition = condition;
        }
        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println("我在等待一个新信号："+name);
                condition.await();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
                System.out.println("我拿到一个新信号："+name);
            }
        }

    }


    static class Producer implements Runnable {
        private String name;
        private Lock lock;
        private Condition condition;

        public Producer(String name,Lock lock,Condition condition) {
            this.name = name;
            this.lock = lock;
            this.condition = condition;
        }
        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println("我拿到锁："+name);
                condition.signalAll();
                System.out.println("我发出一个信号："+name);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();

            }
        }

    }


}
